package com.kefu.chat.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.chat.mapper.ChatChannelMapper;
import com.kefu.chat.mapper.ChatMenuConfigMapper;
import com.kefu.chat.mapper.ChatMenuConfigPlanMapper;
import com.kefu.chat.model.*;
import com.kefu.chat.vo.ChatMenuConfigPlanSearchVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class ChatMenuConfigPlanService extends AbstractKefuService<ChatMenuConfigPlan> {
    @Resource
    private ChatChannelMapper chatChannelMapper;
    @Resource
    private ChatMenuConfigMapper chatMenuConfigMapper;
    @Resource
    private ChatMenuConfigPlanMapper chatMenuConfigPlanMapper;

    @Override
    public ChatMenuConfigPlan getById(Serializable id) {
        ChatMenuConfigPlan info = super.getById(id);
        String menus = info.getMenus();
        if (StrUtil.isNotBlank(menus)) {
            List<String> menuIds = Arrays.asList(menus.split(","));
            List<ChatMenuConfig> chatMenuConfigs = chatMenuConfigMapper.selectList(Wrappers.lambdaQuery(ChatMenuConfig.class)
                    .eq(ChatMenuConfig::getTenantId, KefuContext.getTid()).in(ChatMenuConfig::getId, menuIds));
            info.setChatMenuConfigList(chatMenuConfigs);
        }
        return info;
    }

    @Override
    public void deleteById(String id) {
        super.deleteById(id);
    }

    public Page<ChatMenuConfigPlan> listPlan(ChatMenuConfigPlanSearchVo search) {
        Page<ChatMenuConfigPlan> page = searchLambdaPage(search);
        return page;
    }

    public void batchDeletePlan(List<String> ids) {
        Assert.isTrue(CollUtil.isEmpty(ids), "删除ids不能为空");
        boolean flag = true;
        for (String id :
                ids) {
            Long count = chatChannelMapper.selectCount(Wrappers.lambdaQuery(ChatChannel.class)
                    .eq(ChatChannel::getMenuConfigPlanId, id));
            if (count > 0) {
                flag = false;
            }
        }
        Assert.isTrue(!flag, "方案已经被绑定，不能删除！");
        chatMenuConfigPlanMapper.deleteBatchIds(ids);
        logger.info("批量删除快捷菜单方案:{}", JacksonUtil.toString(ids));
    }
}
